package com.shawn.server.service;

import com.shawn.autoconfig.template.OssTemplate;
import com.shawn.commons.utils.RC;
import com.shawn.dubbo.api.PeachVoiceApi;
import com.shawn.dubbo.api.UserInfoApi;
import com.shawn.model.entity.UserInfo;
import com.shawn.model.mongo.Sound;
import com.shawn.model.vo.SoundVo;
import com.shawn.model.vo.VideoVo;
import com.shawn.server.interceptor.ThreadContext;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author shawn
 * @date 2022年 11月 11日 19:56
 */

@Service
public class PeachBlossomService {

    @DubboReference
    private PeachVoiceApi voiceApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 阿里云存储
     */
    @Autowired
    private OssTemplate ossTemplate;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发布语音
     *
     * @param soundFile 声音文件
     * @return {@link ResponseEntity}
     */
    public ResponseEntity flowVoice(MultipartFile soundFile) throws IOException {
        Long userId = ThreadContext.getUserId();
        //上传至阿里云
        String url = ossTemplate.upLoading(Objects.requireNonNull(soundFile.getOriginalFilename()), soundFile.getInputStream());
        //构造对象
        Sound sound = new Sound();
        sound.setUserId(userId);
        sound.setRemainingTimes(3);
        sound.setSoundUrl(url);
        sound.setCreated(System.currentTimeMillis());
       String id = voiceApi.save(sound);
       return ResponseEntity.ok(id);
    }

    public SoundVo getVoice() {
        Long userId = ThreadContext.getUserId();
        //从redis中获取已获得的声音id
        List<String> voiceIds = redisTemplate.opsForList().range(RC.VOICE_ID_SET_KEY + userId, 0, -1);
        List<ObjectId> ids = new ArrayList<>();
        if (!Objects.isNull(voiceIds)){
            //转换数据格式
             ids = voiceIds.stream().map(ObjectId::new).collect(Collectors.toList());
        }
        //随机从数据库获取一条数据
        Sound sound = voiceApi.getRandomVoice(userId,ids);
        if (Objects.isNull(sound)){
            return new SoundVo();
        }else {
            Long voiceUserId = sound.getUserId();
            UserInfo userInfo = userInfoApi.findDetailById(voiceUserId);
            //将当前数据id存入redis
            redisTemplate.opsForList().rightPush(RC.VOICE_ID_SET_KEY+userId,sound.getId().toHexString());
            //返回数据
            return SoundVo.init(sound,userInfo);
        }
    }
}
